const fs = require("fs");
const path = require("path");

// 递归遍历目录
function walkDir(dir, callback) {
  const files = fs.readdirSync(dir);
  for (const file of files) {
    const fullPath = path.join(dir, file);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      walkDir(fullPath, callback);
    } else if (file.endsWith(".ts") || file.endsWith(".js")) {
      callback(fullPath);
    }
  }
}

// 处理文件
function processFile(filePath) {
  const content = fs.readFileSync(filePath, "utf8");
  const eslintComment =
    "// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n";

  // 移除文件开头的所有 eslint 注释（如果存在）
  let newContent = content.replace(
    /^\/\/ eslint-disable-next-line @typescript-eslint\/ban-ts-comment\n?/,
    ""
  );

  // 替换导入语句
  newContent = newContent.replace(
    /import\s*{\s*request\s*}\s*from\s*['"]umi['"];?/g,
    "import request from '@/utils/request';"
  );

  // 在文件开头添加 eslint 注释
  newContent = eslintComment + newContent;

  // 如果内容有变化，写入文件
  if (content !== newContent) {
    fs.writeFileSync(filePath, newContent, "utf8");
    console.log(`Updated: ${filePath}`);
  }
}

// 要处理的目录
const apiDir = path.join(__dirname, "../src/servers/api");

// 执行处理
if (fs.existsSync(apiDir)) {
  walkDir(apiDir, processFile);
  console.log("File processing completed!");
} else {
  console.log("API directory not found!");
}
